<template>
    <!-- 设备型号保养设置 -->
    <div class="layout-padding">
      <basic-container class="layout-padding-auto layout-padding-view">
        <avue-crud
            v-model='form'
            ref='crud'
            :page='page'
            :data='tableData'
            :table-loading='tableLoading'
            :option='tableOption'
            :before-open="beforeOpen"
            :permission="permissionList"
            @on-load='getList'
            @search-change='searchChange'
            @refresh-change='refreshChange'
            @size-change='sizeChange'
            @current-change='currentChange'
            @row-update='handleUpdate'
            @row-save='handleSave'
            @row-del='rowDel'
            @selection-change='selectionChange'
        >
          <template #menu-left>
            <el-button
                class='filter-item'
                plain
                type='primary'
                icon='el-icon-delete'
                @click='plDelete'
            >
              批量删除
            </el-button>
            <!-- v-if='permissions.om_omrepairmodel_export' -->
            <el-button
                
                class="filter-item"
                plain
                type="primary"
                icon="el-icon-download"
                @click="exportExcel">导出
            </el-button>
          </template>
          <template #modelCode-form='scope'>
            <el-input v-model='form.modelCode' disabled placeholder='请输入'></el-input>
          </template>
          <template #maintenanceContent-form='scope'>
               <avue-crud :data="data1"
                          :option="option1"
                          @on-load='getData'
                          @row-save='addContent'
                          @row-update='editContent'
                          @row-del='delContent'
               >
            </avue-crud>
          </template>
        </avue-crud>
      </basic-container>
    </div>
  </template>
  
  <script>
  import {
    fetchList,
    addObj,
    delObj,
    putObj,
    delAllObj,
    putItemObj,
    delItemObj,
    addItemObj
  } from '/@/api/maintenance/upkeep/config'
  import {tableOption} from '/@/const/crud/maintenance/upkeep/config'
//   import {mapGetters} from 'vuex'
  import {ElLoading} from "element-plus";
  import {getDevList} from "/@/api/maintenance/template";
  
  export default {
    name: 'template',
    data() {
      let _this = this
      return {
        dialogType: '',
        itemIdx: 0,
        parentId: 0,
        infoType: null,
        form: {},
        infoData1: [],
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        selectList: [],
        loading: null,
        value: '',
        data1: [], // 知识库表格数据
        option1: {
          align: 'center',
          index: true,
          indexLabel: '序号',
          selection: true,
          refreshBtn:false,
          indexWidth: 90,
          columnBtn: false,
          searchShow: false,
          tip: false,
          border: true,
          column: [
            {
              label: '保养内容',
              prop: 'maintenanceContent'
            }
          ]
        },
        data2: [],
        option2: {
          align: 'center',
          index: true,
          indexLabel: '序号',
          selection: false,
          indexWidth: 90,
          columnBtn: false,
          searchShow: false,
          tip: false,
          border: true,
          refreshBtn:false,
          column: [
            {
              type: 'datetime',
              label: '维修定期时间',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
              prop: 'data',
              labelWidth: 140,
            }
          ]
        },
        devList:[]
      }
    },
    mounted() {
      getDevList().then((res) => {
        this.devList = res.data.records
      })
    },
    watch: {
      'form.modelName'(newValue, oldValue) {
        if (oldValue || oldValue === '') {
          let o = this.devList.find((item) => {
            return item.id === newValue
          })
          this.form.modelCode = o?.supplierCode
          this.form.devName = o?.name
          this.form.devType = o?.nodeType
        }
      }
    },
    computed: {
    //   ...mapGetters(['permissions']),
      permissionList() {
        return {
        //   getBtn: this.validData(this.permissions.om_omrepairmodel_get, false),
        //   addBtn: this.validData(this.permissions.om_omrepairmodel_add, false),
        //   editBtn: this.validData(this.permissions.om_omrepairmodel_edit, false),
        //   delBtn: this.validData(this.permissions.om_omrepairmodel_del, false)
        }
      }
    },
    methods: {
      addContent(row, done) {
        if (this.dialogType === 'edit') {
          addItemObj({
            equipmentModelId: this.form.id,
            maintenanceContent: row.maintenanceContent
          }).then((res) => {
            this.$message.success('新增成功')
            this.getList(this.page)
          })
        } else {
          this.data1.push(row)
        }
  
        done()
      },
      editContent(row, $index, done) {
        if (this.dialogType === 'edit') {
          putItemObj({
            id: row.id,
            equipmentModelId: row.equipmentModelId,
            maintenanceContent: row.maintenanceContent
          }).then((res) => {
            this.$message.success('修改成功')
            this.getList(this.page)
          }).catch((res) => {
            this.$message.error('修改失败')
            this.getList(this.page)
          })
        } else {
          this.data1.splice($index, 1, {maintenanceContent: row.maintenanceContent, $cellEdit: false, $index})
        }
        done()
      },
      delContent(row, $index) {
        if (this.dialogType === 'edit') {
          this.$confirm('是否确认删除', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
              .then(() => {
                return delItemObj(row.id).then((res) => {
                  this.getList(this.page)
                })
              })
              .then((data) => {
                this.$message.success('删除成功')
              })
              .catch((cancelorerror) => {
              })
  
        } else {
          this.$confirm('是否确认删除', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
              .then(() => {
                return this.data1.splice($index, 1)
              })
              .then((data) => {
                this.$message.success('删除成功')
              })
              .catch((cancelorerror) => {
              })
        }
      },
      getData() {
        this.data1 = this.tableData[this.itemIdx]?.itemsList ?? []
      },
      beforeOpen(done, type) {
        this.itemIdx = this.form.$index
        this.dialogType = type
        this.form.flag = '0'
        done()
      },
      openLoading() {
        this.loading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
      },
      closeLoading() {
        this.loading.close()
      },
      // 全选按钮
      selectionChange(list) {
        this.selectList = list
      },
      // 获取表格数据
      getList(page, params) {
        this.tableLoading = true
        fetchList(
            Object.assign(
                {
                  current: page.currentPage,
                  size: page.pageSize
                },
                params,
                this.searchForm
            )
        )
            .then((response) => {
              this.tableData = response.data.records
              this.page.total = response.data.total
              this.tableLoading = false
              this.getData()
            })
            .catch(() => {
              this.tableLoading = false
            })
      },
      // 删除
      rowDel: function (row, index) {
        this.$confirm('是否确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(function () {
              return delObj(row.id)
            })
            .then((data) => {
              this.$message.success('删除成功')
              this.getList(this.page)
            })
            .catch((cancelorerror) => {
            })
      },
      // 修改更新数据
      handleUpdate: function (row, index, done, loading) {
        putObj(row)
            .then((data) => {
              this.$message.success('修改成功')
              done()
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      // 新增数据
      handleSave: function (row, done, loading) {
        row.modelName = this.form.$modelName
        row.itemsList = this.data1.map((item) => {
          return {maintenanceContent: item.maintenanceContent}
        })
        addObj(row)
            .then((data) => {
              this.$message.success('添加成功')
              done()
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      // 分页大小
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 改变页数
      currentChange(current) {
        this.page.currentPage = current
      },
      // 点击搜索
      searchChange(form, done) {
        this.searchForm = form
        form.modelCode = form.modelName
        delete form.modelName
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新表格
      refreshChange() {
        this.getList(this.page)
      },
      //批量删除
      plDelete() {
        if (this.selectList.length > 0) {
          this.$confirm('是否确认删除以选择的数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
              .then(() => {
                let ids = []
                this.selectList.forEach((data) => {
                  ids.push(data.id)
                })
                this.openLoading()
                return delAllObj(ids).then((res) => {
                  this.closeLoading()
                  this.$message.success('删除成功')
                  this.getList(this.page)
                }).catch(() => {
                  this.closeLoading()
                  this.$message.error('删除失败')
                })
              })
              .then((data) => {
  
              })
              .catch((cancelorerror) => {
              })
        }
      },
      // 导出
      exportExcel() {
        this.downBlobFile('/om/omequipmentmodel/export', this.searchForm, '设备型号保养设备.xlsx')
      },
    }
  }
  </script>
  